<template>
  <div class="profile-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="nav-content">
        <div class="logo">
          <span class="logo-icon">✈️</span>
          <span class="logo-text">旅游平台</span>
        </div>
        <div class="nav-menu">
          <el-menu
            :default-active="'home'"
            mode="horizontal"
            @select="handleMenuSelect"
          >
            <el-menu-item index="home">首页</el-menu-item>
            <el-menu-item index="attractions">景点</el-menu-item>
            <el-menu-item index="travel">旅行</el-menu-item>
            <el-menu-item index="about">关于</el-menu-item>
          </el-menu>
        </div>
        <div class="nav-user">
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userInfo?.avatar">
                {{ userInfo?.nickname?.[0] || 'U' }}
              </el-avatar>
              <span class="username">{{ userInfo?.nickname || '用户' }}</span>
              <el-icon><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                <el-dropdown-item command="favorites">我的收藏</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 个人中心内容 -->
    <div class="profile-content">
      <div class="profile-wrapper">
        <!-- 左侧导航 -->
        <div class="profile-sidebar">
          <el-menu
            :default-active="activeTab"
            class="profile-menu"
            @select="handleTabSelect"
          >
            <el-menu-item index="info">
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </el-menu-item>
            <el-menu-item index="verification">
              <el-icon><DocumentChecked /></el-icon>
              <span>实名认证</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Lock /></el-icon>
              <span>账户安全</span>
            </el-menu-item>
            <el-menu-item index="messages">
              <el-icon><Bell /></el-icon>
              <span>系统消息</span>
              <el-badge :value="unreadCount" v-if="unreadCount > 0" />
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 右侧内容区 -->
        <div class="profile-main">
          <!-- 基本信息 -->
          <div v-if="activeTab === 'info'" class="profile-section">
            <h2 class="section-title">基本信息</h2>
            <el-card shadow="never">
              <el-form
                ref="infoFormRef"
                :model="userForm"
                :rules="infoRules"
                label-width="100px"
              >
                <el-form-item label="头像">
                  <div class="avatar-upload">
                    <el-avatar :size="80" :src="userForm.avatar">
                      {{ userForm.nickname?.[0] || 'U' }}
                    </el-avatar>
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleAvatarUpload"
                      style="margin-left: 20px"
                    >
                      更换头像
                    </el-button>
                    <input
                      ref="avatarInput"
                      type="file"
                      accept="image/*"
                      style="display: none"
                      @change="handleAvatarChange"
                    />
                  </div>
                </el-form-item>

                <el-form-item label="用户名">
                  <el-input v-model="userForm.username" disabled />
                  <span class="form-tip">用户名不可修改</span>
                </el-form-item>

                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                  <div class="flex-input">
                    <el-input
                      v-model="userForm.email"
                      placeholder="请输入邮箱"
                      :disabled="!!userInfo?.email"
                    />
                    <el-tag
                      v-if="userInfo?.email"
                      type="success"
                      style="margin-left: 10px"
                    >
                      已绑定
                    </el-tag>
                    <el-button
                      v-else
                      type="primary"
                      size="small"
                      style="margin-left: 10px"
                      @click="showEmailDialog = true"
                    >
                      绑定邮箱
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                  <div class="flex-input">
                    <el-input
                      v-model="userForm.phone"
                      placeholder="请输入手机号"
                      :disabled="!!userInfo?.phone"
                    />
                    <el-tag
                      v-if="userInfo?.phone"
                      type="success"
                      style="margin-left: 10px"
                    >
                      已绑定
                    </el-tag>
                    <el-button
                      v-else
                      type="primary"
                      size="small"
                      style="margin-left: 10px"
                      @click="showPhoneDialog = true"
                    >
                      绑定手机
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item label="注册时间">
                  <span class="form-text">{{ formatDate(userInfo?.created_at) }}</span>
                </el-form-item>

                <el-form-item label="最后登录">
                  <span class="form-text">{{ formatDate(userInfo?.last_login) || '从未登录' }}</span>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleSaveInfo" :loading="saving">
                    保存修改
                  </el-button>
                  <el-button @click="handleResetInfo">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <!-- 实名认证 -->
          <div v-if="activeTab === 'verification'" class="profile-section">
            <h2 class="section-title">实名认证</h2>
            <el-card shadow="never">
              <div class="verification-status">
                <div v-if="userInfo?.is_verified" class="status-card verified">
                  <el-icon class="status-icon"><CircleCheckFilled /></el-icon>
                  <h3>认证成功</h3>
                  <p>您已完成实名认证</p>
                </div>
                <div v-else class="status-card unverified">
                  <el-icon class="status-icon"><WarningFilled /></el-icon>
                  <h3>未认证</h3>
                  <p>请上传身份证照片完成实名认证</p>
                </div>
              </div>

              <!-- 认证信息展示 -->
              <div v-if="userInfo?.is_verified && verificationDetail" class="verification-detail" style="margin-top: 30px">
                <el-divider>认证信息</el-divider>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="真实姓名">
                    <span style="font-size: 16px; font-weight: 500">{{ verificationDetail.real_name }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="身份证号">
                    <span style="font-size: 16px; font-weight: 500; letter-spacing: 2px">{{ verificationDetail.id_number }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="住址" v-if="verificationDetail.address">
                    {{ verificationDetail.address }}
                  </el-descriptions-item>
                  <el-descriptions-item label="认证时间">
                    {{ formatDateTime(verificationDetail.created_at) }}
                  </el-descriptions-item>
                </el-descriptions>
                
                <!-- 身份证图片展示 -->
                <div v-if="verificationDetail.idcard_image_url" class="idcard-preview" style="margin-top: 20px">
                  <el-image
                    :src="verificationDetail.idcard_image_url"
                    :preview-src-list="[verificationDetail.idcard_image_url]"
                    fit="contain"
                    style="width: 100%; max-width: 600px; border-radius: 8px; border: 1px solid #e4e7ed"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <p style="margin-top: 10px; color: #909399; font-size: 12px">已上传的身份证照片</p>
                </div>
              </div>

              <div v-if="!userInfo?.is_verified" class="verification-upload">
                <el-steps :active="uploadStep" finish-status="success" align-center style="margin: 40px 0">
                  <el-step title="上传身份证" />
                  <el-step title="OCR识别中" />
                  <el-step title="认证完成" />
                </el-steps>

                <div class="upload-area">
                  <el-upload
                    ref="uploadRef"
                    :auto-upload="false"
                    :on-change="handleIdCardChange"
                    :limit="1"
                    accept="image/*"
                    drag
                  >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                      将身份证照片拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持jpg/png格式，文件大小不超过5MB
                      </div>
                    </template>
                  </el-upload>

                  <div v-if="idCardPreview" class="preview-image">
                    <img :src="idCardPreview" alt="身份证预览" />
                    <el-button
                      type="danger"
                      size="small"
                      @click="handleCancelUpload"
                      style="margin-top: 10px"
                    >
                      重新选择
                    </el-button>
                  </div>

                  <div class="upload-actions" v-if="idCardFile">
                    <el-button
                      type="primary"
                      :loading="uploading"
                      @click="handleSubmitVerification"
                    >
                      提交认证
                    </el-button>
                    <el-button @click="handleCancelUpload">取消</el-button>
                  </div>
                </div>

                <el-alert
                  type="info"
                  :closable="false"
                  style="margin-top: 20px"
                >
                  <template #title>
                    <div>
                      <p><strong>认证须知：</strong></p>
                      <ul style="margin: 10px 0; padding-left: 20px">
                        <li>请上传清晰、完整的身份证正面照片</li>
                        <li>确保照片中信息清晰可见，无遮挡、无反光</li>
                        <li>系统将自动识别身份证信息，识别成功后立即完成认证</li>
                        <li>认证信息仅用于身份验证，我们将严格保护您的隐私</li>
                      </ul>
                    </div>
                  </template>
                </el-alert>
              </div>
            </el-card>
          </div>

          <!-- 账户安全 -->
          <div v-if="activeTab === 'security'" class="profile-section">
            <h2 class="section-title">账户安全</h2>
            <el-card shadow="never">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="登录密码">
                  <el-button type="primary" size="small" @click="showPasswordDialog = true">
                    修改密码
                  </el-button>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱绑定">
                  <el-tag :type="userInfo?.email ? 'success' : 'warning'">
                    {{ userInfo?.email || '未绑定' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="手机绑定">
                  <el-tag :type="userInfo?.phone ? 'success' : 'warning'">
                    {{ userInfo?.phone || '未绑定' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="实名认证">
                  <el-tag :type="userInfo?.is_verified ? 'success' : 'warning'">
                    {{ userInfo?.is_verified ? '已认证' : '未认证' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </div>

          <!-- 系统消息 -->
          <div v-if="activeTab === 'messages'" class="profile-section">
            <h2 class="section-title">系统消息</h2>
            <el-card shadow="never">
              <div v-if="messages.length === 0" class="empty-messages">
                <el-empty description="暂无消息" />
              </div>
              <el-timeline v-else>
                <el-timeline-item
                  v-for="message in messages"
                  :key="message.id"
                  :timestamp="formatDateTime(message.timestamp)"
                  :type="message.status === 'success' ? 'success' : 'danger'"
                  placement="top"
                >
                  <el-card>
                    <h4>{{ message.title }}</h4>
                    <p>{{ message.message }}</p>
                    <div v-if="message.status === 'success' && message.data" class="message-data">
                      <el-tag type="success">认证通过</el-tag>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 绑定邮箱对话框 -->
    <el-dialog v-model="showEmailDialog" title="绑定邮箱" width="400px">
      <el-form ref="emailFormRef" :model="emailForm" :rules="emailRules" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEmailDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBindEmail" :loading="binding">确定</el-button>
      </template>
    </el-dialog>

    <!-- 绑定手机对话框 -->
    <el-dialog v-model="showPhoneDialog" title="绑定手机" width="400px">
      <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPhoneDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBindPhone" :loading="binding">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  DocumentChecked,
  Lock,
  Bell,
  ArrowDown,
  CircleCheckFilled,
  WarningFilled,
  UploadFilled,
  Picture
} from '@element-plus/icons-vue'
import { authAPI, profileAPI, qiniuAPI } from '../api/index.js'
import axios from 'axios'

const router = useRouter()

const activeTab = ref('info')
const userInfo = ref(null)
const userForm = ref({})
const saving = ref(false)
const uploading = ref(false)
const binding = ref(false)
const changingPassword = ref(false)
const uploadStep = ref(0)
const idCardFile = ref(null)
const idCardPreview = ref(null)
const showEmailDialog = ref(false)
const showPhoneDialog = ref(false)
const showPasswordDialog = ref(false)
const messages = ref([])
const unreadCount = computed(() => messages.value.filter(m => !m.read).length)
const verificationDetail = ref(null)

const infoFormRef = ref(null)
const emailFormRef = ref(null)
const phoneFormRef = ref(null)
const passwordFormRef = ref(null)
const avatarInput = ref(null)
const uploadRef = ref(null)

const emailForm = reactive({ email: '' })
const phoneForm = reactive({ phone: '' })
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const infoRules = {
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载认证详情
const loadVerificationDetail = async () => {
  try {
    const response = await authAPI.getVerificationDetail()
    if (response.code === 200 && response.data) {
      verificationDetail.value = response.data
    }
  } catch (error) {
    console.error('加载认证详情失败:', error)
    verificationDetail.value = null
  }
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await authAPI.getCurrentUser()
    userInfo.value = response
    userForm.value = {
      username: response.username,
      nickname: response.nickname || '',
      email: response.email || '',
      phone: response.phone || '',
      avatar: response.avatar || ''
    }
    // 如果用户已认证，加载认证详情
    if (response.is_verified) {
      await loadVerificationDetail()
    }
  } catch (error) {
    ElMessage.error('加载用户信息失败')
    console.error(error)
  }
}

// 加载系统消息
const loadMessages = async () => {
  try {
    const response = await profileAPI.getSystemMessages()
    if (response.code === 200 && response.data) {
      messages.value = response.data
    }
  } catch (error) {
    console.error('加载系统消息失败:', error)
  }
}

// 保存用户信息
const handleSaveInfo = async () => {
  if (!infoFormRef.value) return

  await infoFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        await authAPI.updateUserInfo({
          nickname: userForm.value.nickname,
          email: userForm.value.email,
          phone: userForm.value.phone,
          avatar: userForm.value.avatar
        })
        ElMessage.success('保存成功')
        await loadUserInfo()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '保存失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 重置表单
const handleResetInfo = () => {
  userForm.value = {
    username: userInfo.value?.username || '',
    nickname: userInfo.value?.nickname || '',
    email: userInfo.value?.email || '',
    phone: userInfo.value?.phone || '',
    avatar: userInfo.value?.avatar || ''
  }
}

// 头像上传
const handleAvatarUpload = () => {
  avatarInput.value?.click()
}

const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      userForm.value.avatar = e.target.result
      // 这里应该上传到服务器获取URL，暂时使用base64
      ElMessage.info('头像已更新，请保存')
    }
    reader.readAsDataURL(file)
  }
}

// 身份证上传
const handleIdCardChange = (file) => {
  idCardFile.value = file.raw
  const reader = new FileReader()
  reader.onload = (e) => {
    idCardPreview.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
  uploadStep.value = 1
}

// 上传文件到七牛云
const uploadToQiniu = async (file) => {
  // 1. 获取上传token
  const tokenResponse = await qiniuAPI.getUploadToken()
  const token = tokenResponse.uptoken

  // 2. 生成文件key（使用时间戳+随机数确保唯一性）
  const timestamp = Date.now()
  const random = Math.random().toString(36).substring(2, 9)
  const fileExt = file.name.split('.').pop()
  const key = `idcard/${timestamp}_${random}.${fileExt}`

  // 3. 创建FormData并上传到七牛云
  const formData = new FormData()
  formData.append('token', token)
  formData.append('key', key)
  formData.append('file', file)

  // 4. 尝试多个上传域名（按优先级排序）
  // 华东区域 z0, 华北区域 z1, 华南区域 z2
  const uploadEndpoints = [
    'https://up-z0.qiniup.com',  // 华东（优先级最高）
    'https://up-z1.qiniup.com',  // 华北
    'https://up-z2.qiniup.com',  // 华南
    'https://upload.qiniup.com', // 自动选择
    'http://up-z0.qiniup.com',   // HTTP备选（华东）
    'http://up-z1.qiniup.com',   // HTTP备选（华北）
    'http://up-z2.qiniup.com'    // HTTP备选（华南）
  ]

  let lastError = null
  for (const uploadUrl of uploadEndpoints) {
    try {
      console.log(`尝试上传到: ${uploadUrl}`)
      const response = await axios.post(uploadUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 30000,
        // 对于HTTP请求，可能需要设置这些选项
        validateStatus: (status) => status >= 200 && status < 500
      })

      if (response.status === 200 && response.data && response.data.key) {
        // 上传成功，获取完整URL
        try {
          const urlResponse = await qiniuAPI.getUrl({ key: response.data.key })
          console.log('上传成功，文件URL:', urlResponse.url)
          return { success: true, url: urlResponse.url, key: response.data.key }
        } catch (urlError) {
          // 如果获取URL失败，使用默认格式
          console.warn('获取七牛云URL失败，使用默认格式:', urlError)
          return { success: true, url: `https://${key}`, key: response.data.key }
        }
      } else {
        // 响应状态码不是200，继续尝试下一个域名
        console.warn(`${uploadUrl} 返回状态码: ${response.status}`)
        lastError = new Error(`上传失败，状态码: ${response.status}`)
        continue
      }
    } catch (error) {
      // 捕获网络错误，继续尝试下一个域名
      console.warn(`${uploadUrl} 上传失败:`, error.message)
      lastError = error
      continue
    }
  }

  // 所有域名都尝试失败
  console.error('所有上传域名均失败，最后一个错误:', lastError)
  throw lastError || new Error('上传失败：无法连接到七牛云服务器，请检查网络连接')
}

// 提交认证
const handleSubmitVerification = async () => {
  if (!idCardFile.value) {
    ElMessage.warning('请先上传身份证照片')
    return
  }

  uploading.value = true
  try {
    let imageUrl = null
    let imageData = null
    
    // 1. 先尝试上传图片到七牛云（如果失败，使用base64直接提交）
    try {
      ElMessage.info('正在尝试上传图片到七牛云...')
      const uploadResult = await uploadToQiniu(idCardFile.value)
      
      if (uploadResult.success && uploadResult.url) {
        // 七牛云上传成功，使用URL
        imageUrl = uploadResult.url
        ElMessage.success('图片已上传到七牛云')
      } else {
        throw new Error('七牛云上传返回失败')
      }
    } catch (uploadError) {
      // 七牛云上传失败，使用base64直接提交
      console.warn('七牛云上传失败，将使用Base64直接提交:', uploadError)
      ElMessage.warning('七牛云上传失败，将直接提交图片数据...')
      
      // 使用预览图片的base64数据（已经是data:image格式）
      if (idCardPreview.value) {
        imageData = idCardPreview.value
        ElMessage.info('已准备图片数据，正在提交认证...')
      } else {
        // 如果没有预览，重新读取文件
        const reader = new FileReader()
        imageData = await new Promise((resolve, reject) => {
          reader.onload = (e) => resolve(e.target.result)
          reader.onerror = reject
          reader.readAsDataURL(idCardFile.value)
        })
      }
    }

    // 2. 提交认证请求（使用URL或Base64数据）
    const requestData = imageUrl 
      ? { image_url: imageUrl }
      : { image_data: imageData }
    
    ElMessage.info('正在提交认证请求...')
    const response = await profileAPI.verifyIdCard(requestData)
    
    if (response.success) {
      ElMessage.success('认证申请已提交，正在OCR识别中...')
      uploadStep.value = 2
      idCardFile.value = null
      idCardPreview.value = null
      // 定期刷新消息和用户信息，检测认证状态
      setTimeout(loadMessages, 2000)
      startCheckingVerificationStatus()
    } else {
      ElMessage.error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('提交认证失败:', error)
    ElMessage.error(error.response?.data?.detail || error.message || '提交认证失败')
  } finally {
    uploading.value = false
  }
}

const handleCancelUpload = () => {
  idCardFile.value = null
  idCardPreview.value = null
  uploadStep.value = 0
  uploadRef.value?.clearFiles()
  // 停止检查认证状态
  if (verificationCheckTimer.value) {
    clearInterval(verificationCheckTimer.value)
    verificationCheckTimer.value = null
  }
}

// 定时检查认证状态的定时器
const verificationCheckTimer = ref(null)

// 开始检查认证状态（OCR识别完成后会自动认证）
const startCheckingVerificationStatus = () => {
  // 如果已经有定时器在运行，先清除
  if (verificationCheckTimer.value) {
    clearInterval(verificationCheckTimer.value)
  }
  
  let checkCount = 0
  const maxChecks = 60 // 最多检查60次（约2分钟，因为每2秒检查一次）
  
  verificationCheckTimer.value = setInterval(async () => {
    checkCount++
    
    // 超过最大检查次数，停止检查
    if (checkCount > maxChecks) {
      clearInterval(verificationCheckTimer.value)
      verificationCheckTimer.value = null
      return
    }
    
    try {
      // 刷新用户信息
      const response = await authAPI.getCurrentUser()
      
      // 如果认证成功，更新状态
      if (response.is_verified) {
        userInfo.value = response
        uploadStep.value = 3 // 设置为完成状态
        ElMessage.success('认证成功！')
        // 停止检查
        clearInterval(verificationCheckTimer.value)
        verificationCheckTimer.value = null
        // 刷新消息列表
        loadMessages()
        // 加载认证详情
        await loadVerificationDetail()
      }
    } catch (error) {
      console.error('检查认证状态失败:', error)
      // 出错时不停止，继续检查
    }
  }, 2000) // 每2秒检查一次
}

// 绑定邮箱
const handleBindEmail = async () => {
  if (!emailFormRef.value) return

  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      binding.value = true
      try {
        await authAPI.updateUserInfo({ email: emailForm.email })
        ElMessage.success('邮箱绑定成功')
        showEmailDialog.value = false
        await loadUserInfo()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '绑定失败')
      } finally {
        binding.value = false
      }
    }
  })
}

// 绑定手机
const handleBindPhone = async () => {
  if (!phoneFormRef.value) return

  await phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      binding.value = true
      try {
        await authAPI.updateUserInfo({ phone: phoneForm.phone })
        ElMessage.success('手机绑定成功')
        showPhoneDialog.value = false
        await loadUserInfo()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '绑定失败')
      } finally {
        binding.value = false
      }
    }
  })
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true
      try {
        await authAPI.changePassword({
          old_password: passwordForm.oldPassword,
          new_password: passwordForm.newPassword
        })
        ElMessage.success('密码修改成功')
        showPasswordDialog.value = false
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '修改密码失败')
      } finally {
        changingPassword.value = false
      }
    }
  })
}

// 标签页切换
const handleTabSelect = (key) => {
  activeTab.value = key
  if (key === 'messages') {
    loadMessages()
  }
}

// 菜单选择
const handleMenuSelect = (key) => {
  if (key === 'home') {
    router.push('/home')
  }
}

// 用户命令
const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.success('已退出登录')
      router.push('/login')
    })
  } else if (command === 'profile') {
    // 已在个人中心
  } else {
    ElMessage.info(`功能开发中: ${command}`)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadUserInfo()
})

onUnmounted(() => {
  // 组件卸载时清理定时器
  if (verificationCheckTimer.value) {
    clearInterval(verificationCheckTimer.value)
    verificationCheckTimer.value = null
  }
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.logo-icon {
  font-size: 24px;
}

.nav-menu {
  flex: 1;
  display: flex;
  justify-content: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 12px;
  border-radius: 20px;
  transition: background 0.3s;
}

.user-info:hover {
  background: #f5f5f5;
}

.username {
  font-size: 14px;
  color: #333;
}

/* 内容区 */
.profile-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.profile-wrapper {
  display: flex;
  gap: 20px;
}

/* 左侧导航 */
.profile-sidebar {
  width: 200px;
  background: white;
  border-radius: 8px;
  padding: 20px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.profile-menu {
  border-right: none;
}

/* 右侧内容 */
.profile-main {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.profile-section {
  min-height: 500px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

/* 表单样式 */
.form-tip {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.form-text {
  color: #666;
}

.flex-input {
  display: flex;
  align-items: center;
}

.avatar-upload {
  display: flex;
  align-items: center;
}

/* 认证状态 */
.verification-status {
  margin-bottom: 30px;
}

.status-card {
  text-align: center;
  padding: 40px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.status-card.verified {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
}

.status-card.unverified {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
  color: white;
}

.status-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.status-card h3 {
  font-size: 24px;
  margin: 0 0 8px 0;
}

.status-card p {
  font-size: 14px;
  margin: 0;
  opacity: 0.9;
}

/* 上传区域 */
.upload-area {
  margin-top: 30px;
}

.preview-image {
  margin-top: 20px;
  text-align: center;
}

.preview-image img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

/* 消息列表 */
.empty-messages {
  padding: 60px 0;
}

.message-data {
  margin-top: 10px;
}

/* 响应式 */
@media (max-width: 768px) {
  .profile-wrapper {
    flex-direction: column;
  }

  .profile-sidebar {
    width: 100%;
  }
}
</style>

